package com.lostad.app.vert.api.verticle;

import java.util.List;

import org.springframework.context.ApplicationContext;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lostad.app.vert.api.entity.Product;
import com.lostad.app.vert.api.service.ProductService;
import com.lostad.app.vert.core.bean.AjaxJson;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Handler;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.Json;


/**
 * Simple verticle to wrap a Spring service bean - note we wrap the service call
 * in executeBlocking, because we know it's going to be a JDBC call which blocks.
 * As a general principle with Spring beans, the default assumption should be that it will block unless you
 * know for sure otherwise (in other words use executeBlocking unless you know for sure your service call will be
 * extremely quick to respond)
 */
public class ProductConsumer extends AbstractVerticle {

  // Reuse the Vert.x Mapper, alternatively you can use your own.
  private final ObjectMapper mapper = Json.mapper;
  private final ProductService service;

  public ProductConsumer(final ApplicationContext context) {
    //获取spring对象
    service = (ProductService) context.getBean("productService");
  }

 
  @Override
  public void start() throws Exception {
    super.start();
    //查询所有产品
    vertx.eventBus().<String>consumer(ProductSender.LIST_PRODUCTS).handler(msg -> vertx.<String>executeBlocking(future -> {
        try {
      	  //查询数据库
      	  List<Product> list = service.getAllProducts();
      	  AjaxJson json = new AjaxJson(true,null, list);
            future.complete(mapper.writeValueAsString(json));
        } catch (JsonProcessingException e) {
          System.out.println("Failed to serialize result");
          future.fail(e);
        }
      },
      result -> {
        if (result.succeeded()) {
          msg.reply(result.result());
        } else {
          msg.reply(result.cause().toString());
        }
      }));
    
    //保存产品
    vertx.eventBus().<Product>consumer(ProductSender.SAVE_PRODUCT).handler(msg -> vertx.<String>executeBlocking(future -> {
        try {
      	  //查询数据库
      	  Product p = msg.body();
      	  service.save(p);
      	  AjaxJson json = new AjaxJson(true,null, p);
            future.complete(mapper.writeValueAsString(json));
        } catch (JsonProcessingException e) {
          System.out.println("Failed to serialize result");
          future.fail(e);
        }
      },
      result -> {
        if (result.succeeded()) {
          msg.reply(result.result());
        } else {
          msg.reply(result.cause().toString());
        }
      }));
    
    //通过id加载产品
    vertx.eventBus().<String>consumer(ProductSender.LOAD_PRODUCT).handler(loadHandler());
  }
  
  
  
  private Handler<Message<String>> loadHandler() {
	    return msg -> vertx.<String>executeBlocking(future -> {
	          try {
	        	  //查询数据库
	        	  List<Product> list = service.getAllProducts();
	        	  AjaxJson json = new AjaxJson(true,null, list);
	              future.complete(mapper.writeValueAsString(json));
	          } catch (JsonProcessingException e) {
	            System.out.println("Failed to serialize result");
	            future.fail(e);
	          }
	        },
	        result -> {
	          if (result.succeeded()) {
	            msg.reply(result.result());
	          } else {
	            msg.reply(result.cause().toString());
	          }
	        });
	  }

}
